import sys
import os


def format_class_name(class_name):
    if not class_name.endswith('_api'):
        class_name += '_api'
    return class_name


def create_controller(folder, class_name):
    class_name = format_class_name(class_name)
    class_name_camel = ''.join(word.capitalize() for word in class_name.split('_'))
    service_class_name = f"{class_name_camel}Service"
    base_controller_import = "from api.base_controller import BaseController" if folder == "api" else "from admin.base_controller import BaseController"

    content = f"""\
# 导入相关库和模块
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import SessionLocal
import sys
{base_controller_import}
from config.logging import logger
from services.{'admin.' if folder == 'admin' else 'api.'}{class_name}_service import {service_class_name}


# 定义获取数据库会话的依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 定义控制器类
class {class_name_camel}(BaseController):
    def __init__(self):
        super().__init__()
        self.router = APIRouter()


# 使用
{class_name} = {class_name_camel}()
router = {class_name}.router
    """
    return content


def create_service(folder, class_name):
    class_name = format_class_name(class_name)
    class_name_camel = ''.join(word.capitalize() for word in class_name.split('_'))
    service_class_name = f"{class_name_camel}Service"

    content = f"""\
# 导入相关库和模块
from contextlib import contextmanager
from typing import Union
from database import SessionLocal
import sys
from typing import List
from config.logging import logger
from services.database_manager import databaseManager


# 定义服务类
class {service_class_name}:
    def __init__(self, db):
        self.db = db
        self.db_manager = databaseManager(self.db)
    """
    return content


def main():
    if len(sys.argv) != 3:
        print("Usage: python quick_create.py <api/admin> <class_name>")
        sys.exit(1)

    folder, base_class_name = sys.argv[1:3]

    script_directory = os.path.dirname(os.path.abspath(__file__))
    parent_directory = os.path.abspath(os.path.join(script_directory, os.pardir))
    class_name = format_class_name(base_class_name)
    controller_directory = os.path.join(parent_directory, folder, f"{class_name}.py")
    service_directory = os.path.join(parent_directory, 'services', folder, f"{class_name}_service.py")

    if os.path.exists(controller_directory):
        print(f"Controller file '{class_name}.py' already exists in '{folder}' directory. Skipping creation.")
    else:
        controller_content = create_controller(folder, class_name)
        os.makedirs(os.path.dirname(controller_directory), exist_ok=True)
        with open(controller_directory, 'w') as f:
            f.write(controller_content)
        print(f"Controller '{class_name}.py' successfully created in '{folder}'.")

    if os.path.exists(service_directory):
        print(
            f"Service file '{class_name}_service.py' already exists in 'services/{folder}' directory. Skipping creation.")
    else:
        service_content = create_service(folder, class_name)
        os.makedirs(os.path.dirname(service_directory), exist_ok=True)
        with open(service_directory, 'w') as f:
            f.write(service_content)
        print(f"Service '{class_name}_service.py' successfully created in 'services/{folder}'.")


if __name__ == '__main__':
    main()
